#include "includes.h"

char temp[10];
int i;

ISR(INT2_vect)
{
   can_message_t msg;							// can_message shell
    uint8_t rx_status = mcp_rx_status();
    uint8_t buffer = rx_status>>6;
	//	Receive the can message
    can_message_receive(buffer, &msg);
	
	// Check where the message is from
	if(msg.data[0]==14)
	{
		switch (msg.id)
		{	
			case ADD_POINT:
			USART_print("internalpoint++");
			game_add_point(&msg);
			break;
			default:
			USART_print("Unknown id");
			break;
		}
	}
	else
	{
		switch (msg.id)
		{	
			case END_GAME: 
			//	game_end();
				break;
			case PLAYER_READY:
				game_mplay_ready();
			case MULTI_ADD_POINT:
				game_add_point(&msg);
				break;
			case MULTI_GAME_MODE:
				break;
			default:
				USART_print("Unknown id");
				break;
		}
	}
	// Reset the can interrupt flag
    mcp_bit_modify(CAN_INTF,0,(1<<CAN_RX0IF));
}


void can_init()
{
	mcp_init();
}


void can_message_send(uint8_t buffer, can_message_t* msg) 
{
	uint8_t highId	= (uint8_t) (msg->id>>3);
	uint8_t lowId	= (uint8_t) (msg->id<<5);

	switch (buffer) {
		case BUFFER0:
			mcp_write_byte(TXB0SIDH, highId);	
			mcp_write_byte(TXB0SIDL, lowId);
			mcp_write_byte(TXB0DLC, msg->length);
			for(i=0;i<msg->length;i++) {
 				mcp_write_byte(TXB0D0+i, msg->data[i]); 
			}
			mcp_rts(BUFFER0);
			break;
		
		case BUFFER1:
			mcp_write_byte(TXB1SIDH, highId);	
			mcp_write_byte(TXB1SIDL, lowId);
			mcp_write_byte(TXB1DLC, msg->length);
			for(i=0;i<msg->length;i++) {
 				mcp_write_byte(TXB1D0+i, msg->data[i]); 
			}
			mcp_rts(BUFFER1);
			break;

		default:
		//	USART_print("Unknown buffer in can_message_send!\r\n");
			break;
	}
}


void can_message_receive(uint8_t buffer, can_message_t* received)
{
	uint8_t highId;
	uint8_t lowId;
	USART_print("\r\n");

	switch (buffer) {
		case BUFFER0:
//			USART_print("Reading from Buffer 0.\r\n");
			highId = mcp_read_byte(RXB0SIDH);
			highId = highId << 3;
			lowId = mcp_read_byte(RXB0SIDL);
			lowId = lowId >> 5;
			received->id = highId | lowId;

			received->length = mcp_read_byte(RXB0DLC);

			for (i=0;i<received->length;i++) {
				received->data[i] = mcp_read_byte(RXB0D0+i);
			}

			mcp_bit_modify(0x2c, 0x00, 0x01);
			break;

		case BUFFER1:
//			USART_print("Reading from Buffer 1.\r\n");
			highId = mcp_read_byte(RXB1SIDH);
			highId = highId << 3;
			lowId = mcp_read_byte(RXB1SIDL);
			lowId = lowId >> 5;
			received->id = highId | lowId;

			received->length = mcp_read_byte(RXB1DLC);

			for (i=0;i<received->length;i++) {
				received->data[i] = mcp_read_byte(RXB1D0+i);
			}
			mcp_bit_modify(0x2c, 0x00, 0x02);
			break;

		default:
			USART_print("Unknown buffer in can_message_receive!\r\n");
			break;
	}
}
